package com.blb.service.impl;

import com.blb.entity.Brand;
import com.blb.entity.BrandType;
import com.blb.mapper.BrandMapper;
import com.blb.mapper.BrandTypeMapper;
import com.blb.service.IBrandService;
import com.blb.service.IBrandTypeService;
import com.blb.utils.SessionUtils;
import com.blb.utils.UUIDUtils;
import com.mysql.jdbc.StringUtils;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;

import java.util.Date;
import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author wuzhuo
 * @since 2019-07-10
 */
@Service
public class BrandServiceImpl extends ServiceImpl<BrandMapper, Brand> implements IBrandService {

	@Autowired
	private BrandMapper brandMapper;
	
	@Autowired
	private BrandTypeMapper brandTypeMapper;
	
	@Autowired
	private IBrandTypeService brandTypeService;
	
	/**
	 * 添加
	 */
	@Transactional(rollbackFor = Exception.class)
	@Override
	public String add(Brand brand, String comtypes)throws Exception {
		brand.setId(UUIDUtils.getID());
		brand.setCreateUser(SessionUtils.getUserName());
		brand.setCreateTime(new Date());
		brandMapper.insert(brand);
		
		if(!StringUtils.isNullOrEmpty(comtypes)){
			String[] comArr = comtypes.split(",");
			for(String comtype : comArr){
				BrandType brandType = new BrandType();
				brandType.setBrandId(brand.getId());
				brandType.setTypeId(comtype);
				brandTypeMapper.insert(brandType);
			}
		}
		
		return "";
	}
	
	/**
	 * 删除
	 */
	@Transactional(rollbackFor=Exception.class)
	@Override
	public void delete(List<String> ids) throws Exception {
		for (String id : ids) {
			brandMapper.deleteById(id);
			
			brandTypeService.remove(new QueryWrapper<BrandType>().eq("brand_id", id));
		}
	}
	
	/**
	 * 修改
	 */
	@Transactional(rollbackFor=Exception.class)
	@Override
	public void update(Brand brand, String comtypes) throws Exception {
		brand.setUpdateTime(new Date());
		brand.setUpdateUser(SessionUtils.getUserName());
		
		brandMapper.update(brand, new QueryWrapper<Brand>().eq("id", brand.getId()));
		brandTypeService.remove(new QueryWrapper<BrandType>().eq("brand_id", brand.getId()));
		
		if(!StringUtils.isNullOrEmpty(comtypes)){
			String[] typeArr = comtypes.split(",");
			/*for (String typeid : typeArr) {
				brandTypeService.remove(new QueryWrapper<BrandType>().eq("type_id",typeid ));
			}*/
			
			for (String typeid : typeArr) {
				BrandType brandType = new BrandType();
				brandType.setBrandId(brand.getId());
				brandType.setTypeId(typeid);
				brandTypeService.save(brandType);
			}
		}
	}

	@Override
	public List<Brand> getBrand(String brandid) {
		List<Brand> list = brandMapper.selectList(null);
		return list;
	}
		
}
